﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContexts.Supplier;

public partial class Supplier_Price_PriceOnDays : System.Web.UI.Page
{
    private SupplierDataContext supplierContext = new SupplierDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.SupplierLocationDefault;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;


        if (!IsPostBack)
        {
            LoadSuppliers();
            if (!UserAccess.IsCurrentUser(Enums.UserTypes.Admin))
            {
                ddlSuppliers.SelectedValue = UserAccess.CurrentSupplier.SupplierId.ToString();
                tdSupplierControl.Visible = false;
                tdSupplierHead.Visible = false;

                LoadLocations();

                gvPriceOnDays.Visible = false;
                gvSuppPriceOnDays.Visible = true;

                trPercentMargin.Visible = false;
                trActualMargin.Visible = false;

            }
            else
            {
                gvPriceOnDays.Visible = true;
                gvSuppPriceOnDays.Visible = false;
            }
        }
    }

    private void LoadSuppliers()
    {
        ddlSuppliers.DataSource = supplierContext.Suppliers;
        ddlSuppliers.DataTextField = "SupplierName";
        ddlSuppliers.DataValueField = "SupplierId";
        ddlSuppliers.DataBind();
        ddlSuppliers.Items.Insert(0, new ListItem("Select Supplier", "0"));

        ddlLocations.Items.Clear();
        ddlLocations.Items.Insert(0, new ListItem("Select Location", "0"));

        ddlVehicles.Items.Clear();
        ddlVehicles.Items.Insert(0, new ListItem("Select Vehicle", "0"));

        ddlSeasons.Items.Clear();
        ddlSeasons.Items.Insert(0, new ListItem("Select Season", "0"));

        pnlPriceOnDays.Visible = false;
    }
    private void LoadLocations()
    {
        ddlLocations.DataSource = from sl in supplierContext.SupplierLocations
                                  join l in supplierContext.Locations on sl.LocationId equals l.LocationId
                                  where sl.SupplierId == Convert.ToInt32(ddlSuppliers.SelectedValue)
                                  select new { Text = l.LocationName + "-" + sl.City + "-" + sl.PostCode, Value = sl.SupplierLocationId };
        ddlLocations.DataTextField = "Text";
        ddlLocations.DataValueField = "Value";
        ddlLocations.DataBind();
        ddlLocations.Items.Insert(0, new ListItem("Select Location", "0"));

        ddlVehicles.Items.Clear();
        ddlVehicles.Items.Insert(0, new ListItem("Select Vehicle", "0"));

        ddlSeasons.Items.Clear();
        ddlSeasons.Items.Insert(0, new ListItem("Select Season", "0"));

        pnlPriceOnDays.Visible = false;
    }
    private void LoadVehicles()
    {
        ddlVehicles.DataSource = from sv in supplierContext.SupplierVehicles
                                 join slv in supplierContext.SupplierLocationVehicles on sv.SupplierVehicleId equals slv.SupplierVehicleId
                                 where slv.SupplierLocationId == Convert.ToInt32(ddlLocations.SelectedValue)
                                 select new { Text = sv.VehicleCode + "-" + sv.VehicleDescription, Value = slv.SupplierLocationVehicleId };
        ddlVehicles.DataTextField = "Text";
        ddlVehicles.DataValueField = "Value";
        ddlVehicles.DataBind();
        ddlVehicles.Items.Insert(0, new ListItem("Select Vehicle", "0"));

        ddlSeasons.Items.Clear();
        ddlSeasons.Items.Insert(0, new ListItem("Select Season", "0"));
        pnlPriceOnDays.Visible = false;
    }
    private void LoadSeasons()
    {
        var seasons = from sp in supplierContext.PriceOnSeasons
                      where sp.SupplierLocationVehicleId == Convert.ToInt32(ddlVehicles.SelectedValue)
                      orderby sp.StartDate
                      select sp;
        ddlSeasons.Items.Clear();
        foreach (PriceOnSeason ps in seasons)
        {
            ddlSeasons.Items.Add(new ListItem(ps.StartDate.Value.ToString(Constants.DATE_FORMAT) + " to " + ps.EndDate.Value.ToString(Constants.DATE_FORMAT), ps.PriceOnSeasonId.ToString()));
        }

        ddlSeasons.Items.Insert(0, new ListItem("Select Season", "0"));

        pnlPriceOnDays.Visible = false;
    }

    private void ClearAddFields()
    {
        txtStartDayAdd.Text = string.Empty;
        txtEndDayAdd.Text = string.Empty;
        txtRentPriceAdd.Text = string.Empty;
        txtActualMarginAdd.Text = string.Empty;
        txtPercentMarginAdd.Text = string.Empty;
    }

    protected void ddlSuppliers_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadLocations();
    }
    protected void ddlLocations_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadVehicles();
    }
    protected void ddlVehicles_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadSeasons();
    }

    protected void ddlSeasons_SelectedIndexChanged(object sender, EventArgs e)
    {
        pnlPriceOnDays.Visible = (ddlSeasons.SelectedIndex > 0);
        if (pnlPriceOnDays.Visible)
        {
            LoadPriceOnDays();
            ClearAddFields();
        }
    }

    private void LoadPriceOnDays()
    {
        if(gvPriceOnDays.Visible )
        gvPriceOnDays.DataSource = from sp in supplierContext.PriceOnDays
                                   where sp.SupplierLocationVehicleId == Convert.ToInt32(ddlVehicles.SelectedValue)
                                   && sp.PriceOnSeasonId == Convert.ToInt32(ddlSeasons.SelectedValue)
                                   orderby sp.StartDays
                                   select sp;
        if (gvSuppPriceOnDays.Visible)
            gvSuppPriceOnDays.DataSource = from sp in supplierContext.PriceOnDays
                                       where sp.SupplierLocationVehicleId == Convert.ToInt32(ddlVehicles.SelectedValue)
                                       && sp.PriceOnSeasonId == Convert.ToInt32(ddlSeasons.SelectedValue)
                                       orderby sp.StartDays
                                       select sp;
        gvPriceOnDays.DataBind();
        gvSuppPriceOnDays.DataBind();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        PriceOnDay pd = new PriceOnDay
        {
            SupplierLocationVehicleId = Convert.ToInt32(ddlVehicles.SelectedValue),
            PriceOnSeasonId = Convert.ToInt32(ddlSeasons.SelectedValue),
            StartDays = Convert.ToInt32(txtStartDayAdd.Text),
            EndDays = Convert.ToInt32(txtEndDayAdd.Text),
            RentPrice = Convert.ToDecimal(txtRentPriceAdd.Text),
            ActualMargin = !string.IsNullOrEmpty(txtActualMarginAdd.Text) ? Convert.ToDecimal(txtActualMarginAdd.Text) : 0,
            PercentMargin = !string.IsNullOrEmpty(txtPercentMarginAdd.Text) ? Convert.ToDecimal(txtPercentMarginAdd.Text) : 20
        };

        pd.RentSellPrice = Helper.GetSellPrice(pd.RentPrice.Value, pd.ActualMargin.Value, pd.PercentMargin.Value);

        supplierContext.PriceOnDays.InsertOnSubmit(pd);
        supplierContext.SubmitChanges();

        ClearAddFields();

        gvPriceOnDays.EditIndex = -1;
        LoadPriceOnDays();

    }
    protected void gvPriceOnDays_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        ClearAddFields();
        gvPriceOnDays.EditIndex = -1;
        LoadPriceOnDays();
    }
    protected void gvPriceOnDays_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            PriceOnDay pd = e.Row.DataItem as PriceOnDay;
            if (pd != null)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    TextBox txtStartDaysEdit = (TextBox)e.Row.FindControl("txtStartDaysEdit");
                    TextBox txtEndDaysEdit = (TextBox)e.Row.FindControl("txtEndDaysEdit");
                    TextBox txtPercentMarginEdit = (TextBox)e.Row.FindControl("txtPercentMarginEdit");
                    TextBox txtActualMarginEdit = (TextBox)e.Row.FindControl("txtActualMarginEdit");
                    TextBox txtRentPriceEdit = (TextBox)e.Row.FindControl("txtRentPriceEdit");

                    txtStartDaysEdit.Text = pd.StartDays.Value.ToString();
                    txtEndDaysEdit.Text = pd.EndDays.Value.ToString();
                    txtRentPriceEdit.Text = pd.RentPrice.Value.ToString(Constants.DECIMAL_FORMAT);

                    if (pd.PercentMargin.HasValue)
                        txtPercentMarginEdit.Text = pd.PercentMargin.Value.ToString(Constants.DECIMAL_FORMAT);
                    if (pd.ActualMargin.HasValue)
                        txtActualMarginEdit.Text = pd.ActualMargin.Value.ToString(Constants.DECIMAL_FORMAT);

                }
                else if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    Label lblStartDate = (Label)e.Row.FindControl("lblStartDays");
                    Label lblEndDate = (Label)e.Row.FindControl("lblEndDays");
                    Label lblRentPrice = (Label)e.Row.FindControl("lblRentPrice");
                    Label lblPercentMargin = (Label)e.Row.FindControl("lblPercentMargin");
                    Label lblActualMargin = (Label)e.Row.FindControl("lblActualMargin");

                    lblStartDate.Text = pd.StartDays.Value.ToString();
                    lblEndDate.Text = pd.EndDays.Value.ToString();
                    lblRentPrice.Text = pd.RentPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    if (pd.PercentMargin.HasValue)
                        lblPercentMargin.Text = pd.PercentMargin.Value.ToString(Constants.DECIMAL_FORMAT);
                    if (pd.ActualMargin.HasValue)
                        lblActualMargin.Text = pd.ActualMargin.Value.ToString(Constants.DECIMAL_FORMAT);

                    Helper.ApplyDeleteConfirmMsg(e, 6);
                }
            }


        }
    }
    protected void gvPriceOnDays_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
    protected void gvPriceOnDays_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(gvPriceOnDays.DataKeys[e.RowIndex].Value);
        PriceOnDay pd = supplierContext.PriceOnDays.FirstOrDefault(p => p.PriceOnDaysId == id);
        supplierContext.PriceOnDays.DeleteOnSubmit(pd);
        supplierContext.SubmitChanges();
        gvPriceOnDays.EditIndex = -1;
        LoadPriceOnDays();
    }
    protected void gvPriceOnDays_RowEditing(object sender, GridViewEditEventArgs e)
    {
        ClearAddFields();
        gvPriceOnDays.EditIndex = e.NewEditIndex;
        LoadPriceOnDays();
    }
    protected void gvPriceOnDays_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {

    }
    protected void gvPriceOnDays_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gvPriceOnDays.Rows[Convert.ToInt32(e.RowIndex)];
        TextBox txtStartDaysEdit = (TextBox)row.FindControl("txtStartDaysEdit");
        TextBox txtEndDaysEdit = (TextBox)row.FindControl("txtEndDaysEdit");
        TextBox txtRentPriceEdit = (TextBox)row.FindControl("txtRentPriceEdit");
        TextBox txtPercentMarginEdit = (TextBox)row.FindControl("txtPercentMarginEdit");
        TextBox txtActualMarginEdit = (TextBox)row.FindControl("txtActualMarginEdit");

        int id = Convert.ToInt32(gvPriceOnDays.DataKeys[e.RowIndex].Value);
        PriceOnDay pd = supplierContext.PriceOnDays.FirstOrDefault(p => p.PriceOnDaysId == id);

        if (pd != null)
        {
            pd.StartDays = Convert.ToInt32(txtStartDaysEdit.Text);
            pd.EndDays = Convert.ToInt32(txtEndDaysEdit.Text);
            pd.RentPrice = Convert.ToDecimal(txtRentPriceEdit.Text);
            pd.PercentMargin = Convert.ToDecimal(txtPercentMarginEdit.Text);
            pd.ActualMargin = Convert.ToDecimal(txtActualMarginEdit.Text);
            supplierContext.SubmitChanges();
        }

        ClearAddFields();
        gvPriceOnDays.EditIndex = -1;
        LoadPriceOnDays();
    }

    #region Supplier Grid View
    protected void gvSuppPriceOnDays_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        ClearAddFields();
        gvSuppPriceOnDays.EditIndex = -1;
        LoadPriceOnDays();
    }
    protected void gvSuppPriceOnDays_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            PriceOnDay pd = e.Row.DataItem as PriceOnDay;
            if (pd != null)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    TextBox txtStartDaysEdit = (TextBox)e.Row.FindControl("txtStartDaysEdit");
                    TextBox txtEndDaysEdit = (TextBox)e.Row.FindControl("txtEndDaysEdit");
                    //TextBox txtPercentMarginEdit = (TextBox)e.Row.FindControl("txtPercentMarginEdit");
                    //TextBox txtActualMarginEdit = (TextBox)e.Row.FindControl("txtActualMarginEdit");
                    TextBox txtRentPriceEdit = (TextBox)e.Row.FindControl("txtRentPriceEdit");

                    txtStartDaysEdit.Text = pd.StartDays.Value.ToString();
                    txtEndDaysEdit.Text = pd.EndDays.Value.ToString();
                    txtRentPriceEdit.Text = pd.RentPrice.Value.ToString(Constants.DECIMAL_FORMAT);

                    //if (pd.PercentMargin.HasValue)
                    //    txtPercentMarginEdit.Text = pd.PercentMargin.Value.ToString(Constants.DECIMAL_FORMAT);
                    //if (pd.ActualMargin.HasValue)
                    //    txtActualMarginEdit.Text = pd.ActualMargin.Value.ToString(Constants.DECIMAL_FORMAT);

                }
                else if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    Label lblStartDate = (Label)e.Row.FindControl("lblStartDays");
                    Label lblEndDate = (Label)e.Row.FindControl("lblEndDays");
                    Label lblRentPrice = (Label)e.Row.FindControl("lblRentPrice");
                    //Label lblPercentMargin = (Label)e.Row.FindControl("lblPercentMargin");
                    //Label lblActualMargin = (Label)e.Row.FindControl("lblActualMargin");

                    lblStartDate.Text = pd.StartDays.Value.ToString();
                    lblEndDate.Text = pd.EndDays.Value.ToString();
                    lblRentPrice.Text = pd.RentPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    //if (pd.PercentMargin.HasValue)
                    //    lblPercentMargin.Text = pd.PercentMargin.Value.ToString(Constants.DECIMAL_FORMAT);
                    //if (pd.ActualMargin.HasValue)
                    //    lblActualMargin.Text = pd.ActualMargin.Value.ToString(Constants.DECIMAL_FORMAT);

                    Helper.ApplyDeleteConfirmMsg(e, 4);
                }
            }


        }
    }
    protected void gvSuppPriceOnDays_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
    protected void gvSuppPriceOnDays_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(gvSuppPriceOnDays.DataKeys[e.RowIndex].Value);
        PriceOnDay pd = supplierContext.PriceOnDays.FirstOrDefault(p => p.PriceOnDaysId == id);
        supplierContext.PriceOnDays.DeleteOnSubmit(pd);
        supplierContext.SubmitChanges();
        gvSuppPriceOnDays.EditIndex = -1;
        LoadPriceOnDays();
    }
    protected void gvSuppPriceOnDays_RowEditing(object sender, GridViewEditEventArgs e)
    {
        ClearAddFields();
        gvSuppPriceOnDays.EditIndex = e.NewEditIndex;
        LoadPriceOnDays();
    }
    protected void gvSuppPriceOnDays_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {

    }
    protected void gvSuppPriceOnDays_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gvSuppPriceOnDays.Rows[Convert.ToInt32(e.RowIndex)];
        TextBox txtStartDaysEdit = (TextBox)row.FindControl("txtStartDaysEdit");
        TextBox txtEndDaysEdit = (TextBox)row.FindControl("txtEndDaysEdit");
        TextBox txtRentPriceEdit = (TextBox)row.FindControl("txtRentPriceEdit");
        //TextBox txtPercentMarginEdit = (TextBox)row.FindControl("txtPercentMarginEdit");
        //TextBox txtActualMarginEdit = (TextBox)row.FindControl("txtActualMarginEdit");

        int id = Convert.ToInt32(gvSuppPriceOnDays.DataKeys[e.RowIndex].Value);
        PriceOnDay pd = supplierContext.PriceOnDays.FirstOrDefault(p => p.PriceOnDaysId == id);

        if (pd != null)
        {
            pd.StartDays = Convert.ToInt32(txtStartDaysEdit.Text);
            pd.EndDays = Convert.ToInt32(txtEndDaysEdit.Text);
            pd.RentPrice = Convert.ToDecimal(txtRentPriceEdit.Text);
            //pd.PercentMargin = Convert.ToDecimal(txtPercentMarginEdit.Text);
            //pd.ActualMargin = Convert.ToDecimal(txtActualMarginEdit.Text);

            pd.RentSellPrice = Helper.GetSellPrice(pd.RentPrice.Value, pd.ActualMargin.Value, pd.PercentMargin.Value);

            supplierContext.SubmitChanges();
        }

        ClearAddFields();
        gvSuppPriceOnDays.EditIndex = -1;
        LoadPriceOnDays();
    }
    #endregion
}
